<template>
  <div>
    <!-- 添加对话框 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" width="40%">
      <el-form :model="salesorderlist" >
        <el-form-item label="订单号" prop="orderNum">
          <el-input v-model="salesorderlist.orderNum" autocomplete="off" style="width:300px"></el-input>
        </el-form-item>
        <el-form-item label="客户名称" prop="cid">
          <el-select v-model="salesorderlist.cid" placeholder="请选择">
            <el-option v-for="item in customerOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
          <!-- <el-input v-model="salesorderlist.cName" autocomplete="off" style="width:300px" ></el-input> -->
        </el-form-item>
        <el-form-item label="完成状态" prop="finishFlag">
          <el-select v-model="salesorderlist.finishFlag" placeholder="请选择">
            <el-option v-for="item in finishFlagOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品编码" prop="pcode">
          <el-input v-model="salesorderlist.pcode" autocomplete="off" style="width:300px" disabled></el-input>
        </el-form-item>
        <el-form-item label="产品名称" prop="pid">
          <el-select v-model="salesorderlist.pid" placeholder="请选择" @change="handleProductChange">
            <el-option v-for="item in productOptions" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
          <!-- <el-input v-model="salesorderlist.pname" autocomplete="off" style="width:300px" ></el-input> -->
        </el-form-item>
        <el-form-item label="购买数量" prop="pNum">
          <el-input v-model="salesorderlist.pnum" autocomplete="off" style="width:300px"></el-input>
        </el-form-item>
        <el-form-item label="产品单位" prop="unit">
          <el-input v-model="salesorderlist.unit" autocomplete="off" style="width:300px" disabled></el-input>
        </el-form-item>
        <el-form-item label="产品单价" prop="price">
          <el-input v-model="salesorderlist.price" autocomplete="off" style="width:300px"></el-input>
        </el-form-item>
        <el-form-item label="应付金额" prop="money">
          <el-input v-model="salesorderlist.money" @focus="calculateMoney" autocomplete="off" style="width:300px"
            readonly placeholder="点击展示金额">
          </el-input>
        </el-form-item>
        <!-- 创建时间 -->
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker v-model="salesorderlist.createTime" type="date" placeholder="选择日期时间" value-format="yyyy-MM-dd"
            style="width: 300px">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div>
        <el-button type="primary" @click="addSalesOrderList">提交</el-button>
        <el-button @click="dialogFormVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  
    <!-- 查询表单 -->
    <el-form :inline="true" :model="keyword" ref="searchForm" class="demo-form-inline">
      <el-form-item>
        <el-button type="danger" size="small" @click="deleteBatch" icon="el-icon-delete">删除</el-button>
        <el-button type="warning" size="small" @click="openAddDialog" icon="el-icon-plus">添加</el-button>
      </el-form-item>
      <el-form-item label="订单号" prop="orderNum">
        <el-input size="small" clearable v-model="keyword.orderNum" placeholder="订单号"></el-input>
      </el-form-item>
      <el-form-item label="完成状态" prop="finishFlag">
        <el-select v-model="keyword.finishFlag" placeholder="请选择完成状态">
          <el-option label="已完成" value=1></el-option>
          <el-option label="未完成" value=0></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="search" icon="el-icon-search">查询</el-button>
        <el-button type="primary" plain size="small" @click="resetSearchForm('searchForm')" icon="el-icon-refresh">
          重置
        </el-button>

      </el-form-item>
    </el-form>
    <!-- 数据展示表 -->
    <el-table v-loading="loading" :data="orderList" tooltip-effect="dark" style="width: 100%"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="订单号" width="120" prop="orderNum"> </el-table-column>
      <el-table-column label="客户姓名" width="120" prop="customer.name"> </el-table-column>
      <el-table-column label="完成状态" width="120" prop="finishFlag">
        <template slot-scope="scope">
          <el-tag :type="scope.row.finishFlag == 1 ? '' : 'danger'">
            <span>{{ scope.row.finishFlag == 1 ? '已完成' : '未完成' }}</span>
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="产品编码" width="120" prop="product.pcode"></el-table-column>
      <el-table-column label="产品名称" width="120" prop="product.name"></el-table-column>
      <el-table-column label="购买产品数量" width="120" prop="pnum"></el-table-column>
      <el-table-column label="产品单价" width="120" prop="price"></el-table-column>
      <el-table-column label="产品单位" width="120" prop="product.unit"></el-table-column>
      <el-table-column label="应付金额" width="120" prop="money"></el-table-column>
      <el-table-column label="创建时间" width="150" prop="createTime"></el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['md:measure:edit']">修改</el-button> -->
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['md:measure:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页插件 -->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
      :page-sizes="[3, 5, 10]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>
  </div>
</template>
<script>
import { orderList, deleteByIds, addSalesOrderList, updateSalesOrderList, getCustomerList, getProductList, deleteById } from '@/api/salesOeder'
export default {
  data() {
    return {

      updateDialogFormVisible: false,
      dialogFormVisible: false,
      loading: false,
      orderList: {},
      pageNum: 1,
      pageSize: 10,
      total: 0,
      currentPage: 1,
      ids: [],
      selectionRowArr: [],
      keyword: {
        orderNum: '',
        finishFlag: ''
      },
      updateSalesorderlist: {
        orderNum: '',
        cid: '',
        pid: '',
        pnum: 0,
        unit: '',
        price: 0,
        money: '',
        createTime: '',
        finishFlag: '',
      },
      salesorderlist: {
        orderNum: '',
        cid: '',
        pid: '',
        pnum: 0,
        unit: '',
        price: 0,
        money: '',
        createTime: '',
        finishFlag: '',
      },

      customerOptions: [],
      productOptions: [],
      finishFlagOptions: [
        {
          label: '未完成',
          value: '0'
        }, {
          label: '已完成',
          value: '1'
        }
      ],
      title:''

    }
  },
  methods: {

    showList() {
      this.listLoading = true
      orderList(
        {
          orderNum: this.keyword.orderNum,
          finishFlag: this.keyword.finishFlag,
          pageNum: this.pageNum,
          pageSize: this.pageSize
        }
      ).then(response => {
        console.log("salesOrder  line233", response)
        this.orderList = response.data.list
        this.total = response.data.total
        this.listLoading = false
      })

    },
    handleSizeChange(val) {
      this.pageSize = val
      this.showList()
    },
    handleCurrentChange(val) {
      this.pageNum = val
      this.showList()
    },
    handleSelectionChange(selectionRowArr) {
      this.ids = [];
      for (let i = 0; i < selectionRowArr.length; i++) {
        this.ids.push(selectionRowArr[i].id)
      }
    },
    // 重置表单
    resetSearchForm() {
      this.keyword = {}
      this.showList()
    },
    // 查询
    search() {
      this.pageNum = 1
      this.showList()
    },
    // 删除
    handleDelete(row) {
      console.log("line215", row)
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteById({ id: row.id }).then(res => {
          if (res.code == 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.showList();
          } else {
            this.$message({
              type: 'error',
              message: '删除失败!'
            });
          }
        })
      })

    },
    // 批量删除
    deleteBatch() {
      this.$confirm('此操作将永久删除' + this.ids.length + '条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //delBatch  刚才api/unit.js中一个axios方法
        deleteByIds(this.ids).then(response => {
          // console.log("md line 151:", response)
          if (response.code == 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getList()
          }

        })
      })
    },
    openAddDialog() {
      this.title = '添加'
      this.dialogFormVisible = true
      this.generateOrderNumber()
      this.getCustomerData()
      this.getProductData()
      this.salesorderlist.finishFlag = '0'
    },
    generateOrderNumber() {
      const prefix = 'SO';
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');
      console.log(`${prefix}${year}${month}${day}${hours}${minutes}${seconds}`)
      var myOrderNum = `${prefix}${year}${month}${day}${hours}${minutes}${seconds}`
      this.salesorderlist.orderNum = myOrderNum
    },
    handleUpdate(row) {
      this.title = '修改'
      this.updateDialogFormVisible = true
      this.updateSalesorderlist = {
        id: row.id, // 如果有唯一标识符，确保保存原始 ID
        orderNum: row.orderNum,
        cid: row.customer.id, // 客户 ID，用于 el-select 匹配
        pid: row.product.id, // 产品 ID，用于 el-select 匹配
        pnum: row.pnum,
        unit: row.product.unit,
        pcode: row.product.pcode,
        price: row.price,
        money: row.money,
        createTime: row.createTime,
        finishFlag: row.finishFlag.toString()
      }
    },
    addSalesOrderList() {
      console.log("line 252 ", this.salesorderlist)
      addSalesOrderList(this.salesorderlist).then(res => {
        if (res.code == 200) {
          this.$message.success('添加成功')
          this.resetForm();
          this.dialogFormVisible = false
          this.showList()

        } else {
          this.$message.error('添加失败')
          this.resetForm();
        }
      })
    },
    getCustomerData() {
      getCustomerList().then(response => {
        console.log("index line259", response)
        this.customerOptions = response.data.map(item => ({
          value: item.id,
          label: item.name
        }))
      })
    },
    getProductData() {
      getProductList().then(response => {
        console.log("index line 375", response)
        this.productOptions=response.data
      });
    },
    updateSalesorderlist() {

      const updateProductOptions = this.updateProductOptions.find(item => item.value === productId);
      if (updateProductOptions) {
        this.updateSalesorderlist.pcode = updateProductOptions.pcode;
        this.updateSalesorderlist.unit = updateProductOptions.unit;
        this.updateSalesorderlist.price = updateProductOptions.price;
      }
    },
    handleProductChange(productId) {
      const selectedProduct = this.productOptions.find(item => item.id === productId);
      if (selectedProduct) {
        this.salesorderlist.pcode = selectedProduct.pcode;
        this.salesorderlist.unit = selectedProduct.unit;
        this.salesorderlist.price = selectedProduct.price;


      }
    },
    calculateMoney() {
      const price = parseFloat(this.salesorderlist.price) || 0;
      const pnum = parseInt(this.salesorderlist.pnum) || 0;
      this.salesorderlist.money = (price * pnum).toFixed(2);
    },
    resetForm() {
      this.salesorderlist = {
        orderNum: '',
        cid: '',
        pid: '',
        pnum: 0,
        unit: '',
        price: 0,
        money: 0,
        createTime: '',
        finishFlag: '0' // 默认未完成
      };
    }
  },
  created() {
    this.showList()
  },
  computed: {
    money: function () {
      return this.salesorderlist.price * this.salesorderlist.num;
    }
  },


}
</script>
<style scoped></style>